package com.dituhui.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import com.dituhui.gps.service.GetPos;
import com.dituhui.gps.vo.GPSLine;
import com.dituhui.gps.vo.GPSPoint;
import com.dituhui.tool.io.Constants;
import com.dituhui.tool.util.StringUtil;

import net.sf.json.JSONObject;

/**
 * GPS分布查询服务
 * 
 * @author liweigu
 * 
 */
public class GPSPos extends HttpServlet {
	private static Logger LOGGER = Logger.getLogger(GPSPos.class);
	private String redisHost;
	private int redisPort;
	private String redisPwd;

	public void init() throws ServletException {
		redisHost = Constants.getValue("REDIS.HOST", "gps_config.properties");
		redisPort = Integer.parseInt(Constants.getValue("REDIS.PORT", "gps_config.properties"));
		redisPwd = Constants.getValue("REDIS.PWD", "gps_config.properties");
	}

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String cmd = request.getParameter("cmd");
		String userKey = request.getParameter("k");
		if (userKey == null || userKey.length() == 0 || userKey.equals(StringUtil.NULL)) {
			// 空值置为null
			userKey = null;
		}
		// 跨域访问
		String callbacks = (request.getParameter("callbacks") != null) ? request.getParameter("callbacks") : null;
		response.setCharacterEncoding("UTF-8");
		PrintWriter out = response.getWriter();
		if (cmd == null) {
			out.print("参数cmd非法");
		} else {
			String content = null;
			try {
				List<GPSPoint> gpsPoints = GetPos.getGPSList(userKey, redisHost, redisPort, redisPwd);
				GPSLine gpsLine = new GPSLine();
				gpsLine.setGPSPoints(gpsPoints);
				content = gpsLine.toCSVString();
			} catch (Exception e) {
				String message = "seacrhRealtime发生异常。";
				LOGGER.warn(message, e);
			}

			if (content == null) {
				content = "NoData";
			}
			StringBuilder output = new StringBuilder();
			if (callbacks != null && callbacks.length() > 0) {
				output.append(callbacks);
				output.append("(");
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("data", content);
				output.append(jsonObject.toString());
				output.append(")");
			} else {
				output.append(content);
			}
			out.print(output.toString());
			out.flush();
			out.close();
		}
	}
}
